package rensoft.android.xml;

import org.xml.sax.InputSource;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import rensoft.java.xml.impl.DocumentImpl;

import rensoft.android.xml.w3c.impl.W3CDocument;

import rensoft.java.xml.XML;


import static rensoft.java.lang.Lang.exception;


public class XmlImpl implements XML {

  private DocumentBuilder builder;

  public rensoft.java.xml.Document load(String text) {
    try {
      DocumentBuilder builder = getBuilder();
      W3CDocument doc = new W3CDocument(builder.parse(new InputSource(new StringReader(text))));
      return new DocumentImpl(doc);
    } catch (java.lang.Exception ex) {
      throw exception(ex);
    }
  }

  private DocumentBuilder getBuilder() throws ParserConfigurationException {
    if (builder == null) builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    return builder;
  }
}
